package patrol.mobile.com.mobilepatrol.activity.road_survey;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.bean.RouteSurveyTaskBean;
import patrol.mobile.com.mobilepatrol.bean.RouteSurveyTaskDetailBean;
import patrol.mobile.com.mobilepatrol.bean.RouteSurveyTaskItemBO;
import patrol.mobile.com.mobilepatrol.bean.TrafficInvestBaseInfo;
import patrol.mobile.com.mobilepatrol.bean.User;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.DateUtil;
import patrol.mobile.com.mobilepatrol.utils.PKCreator;
import patrol.mobile.com.mobilepatrol.utils.UIHelper;


/**
 * Created by 健 on 2014/8/26.
 */
public class TrafficInvestBaseInfoActivity extends BaseActivity {

    private TrafficInvestBaseInfo investBaseInfo;
    private List<RouteSurveyTaskItemBO> roadItemInfos;
    
    private User userInfo;
    private Button nextStep;

    private Spinner surveyLineSpi;
    private Spinner surveyRoadLevelSpi;
    private Spinner surveyRoadTypeSpi;
    private Spinner surveyDirectSpi;
    private Spinner surveyRoadItemSpi;
    private EditText surveyDate;
    private EditText surveyPeople;

    private EditText startKm_et;
    private EditText startMeter_et;
    private EditText endKm_et;
    private EditText endMeter_et;

    private Spinner surveyTypeSpi;
    private Spinner surveySelectSpi;
    private Spinner surveyTaskSpi;
    private CheckBox check_type1;
    private CheckBox check_type2;
    private CheckBox check_type3;
    private CheckBox check_type4;
//    private String investBaseInfoID;
private DBHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void initData() {
        dbHelper=new DBHelper(this);
        userInfo= UserManager.getUser();
        Logger.d(userInfo.org_No+" "+userInfo.orgtype);
//        investBaseInfoID = getIntent().getStringExtra("id");
//        if (investBaseInfoID!=null){
//            investBaseInfo = RoadSurveyManager.getTrafficInvestBaseInfo(investBaseInfoID);
//        }
        investBaseInfo= (TrafficInvestBaseInfo) getIntent().getSerializableExtra(UIHelper.INVEST_INFO);

      //  surveyDirectSpi.setAdapter(getArrayAdapter(getResources().getStringArray(R.array.invest_direct)));
        surveyTypeSpi.setAdapter(getArrayAdapter(getResources().getStringArray(R.array.invest_type)));
       // surveySelectSpi.setAdapter(getArrayAdapter(getResources().getStringArray(R.array.invest_select)));
        if(userInfo.orgtype.equals("分局")){
            surveyTaskSpi.setAdapter(getArrayAdapter(dbHelper.getTaskInfoAll(userInfo.bmcode)));
        }else {
            surveyTaskSpi.setAdapter(getArrayAdapter(dbHelper.getTaskInfoAll()));
        }
       // surveyRoadTypeSpi.setAdapter(getArrayAdapter(getResources().getStringArray(R.array.invest_roadType)));
        
        if(investBaseInfo!=null){
           // selectedItem(surveyDirectSpi,investBaseInfo.getSurveyWay());
            selectedItem(surveyTypeSpi,investBaseInfo.getSurveyType());
           // selectedItem(surveySelectSpi,investBaseInfo.getSurveySelect());
            selectedItem(surveyTaskSpi,investBaseInfo.getSurveyTask());
            
            List<String> roadDirect=new ArrayList<String>();
            roadDirect.add(investBaseInfo.getSurveyWay());
            surveyDirectSpi.setAdapter(getArrayAdapter(roadDirect));

            List<String> roadType=new ArrayList<String>();
            roadType.add(investBaseInfo.getRoudBedType());
            surveyRoadTypeSpi.setAdapter(getArrayAdapter(roadType));

            List<String> roadLevel=new ArrayList<String>();
            roadLevel.add(investBaseInfo.getRoadLevel());
            surveyRoadLevelSpi.setAdapter(getArrayAdapter(roadLevel));

            List<String> roadItem=new ArrayList<String>();
            roadItem.add("("+investBaseInfo.getStartPot()+investBaseInfo.getStartPotKm()+"+"+investBaseInfo.getStartPotMeter()
            +","+investBaseInfo.getStartPot()+investBaseInfo.getEndPotKm2()+"+"+investBaseInfo.getEndPotMeter2()+")");
            surveyRoadItemSpi.setAdapter(getArrayAdapter(roadItem));
            
            //  selectedItem(surveyRoadTypeSpi,investBaseInfo.getRoudBedType());

            RouteSurveyTaskBean task= (RouteSurveyTaskBean) surveyTaskSpi.getSelectedItem();
            surveyLineSpi.setAdapter(getArrayAdapter(dbHelper.getSurveyRouteInfo(task.getiD())));
            selectedItem(surveyLineSpi,investBaseInfo.getSurveyLine());

            surveyPeople.setText(investBaseInfo.getSurveyer());
            surveyDate.setText(investBaseInfo.getSurveyDate());
            startKm_et.setText(investBaseInfo.getStartPotKm() + "");
            startMeter_et.setText(investBaseInfo.getStartPotMeter() + "");
            endKm_et.setText(investBaseInfo.getEndPotKm2() + "");
            endMeter_et.setText(investBaseInfo.getEndPotMeter2() + "");

            surveyDirectSpi.setEnabled(false);
            surveyTypeSpi.setEnabled(false);
           // surveySelectSpi.setEnabled(false);
            surveyRoadItemSpi.setEnabled(false);
            surveyRoadLevelSpi.setEnabled(false);
            surveyRoadTypeSpi.setEnabled(false);
            surveyTaskSpi.setEnabled(false);
            surveyLineSpi.setEnabled(false);
            startKm_et.setEnabled(false);
            startMeter_et.setEnabled(false);
            endKm_et.setEnabled(false);
            endMeter_et.setEnabled(false);
            if (investBaseInfo.lumian==1){
                check_type1.setChecked(true);
            }
            if (investBaseInfo.luji==1){
                check_type2.setChecked(true);
            }
            if (investBaseInfo.yanxian==1){
                check_type3.setChecked(true);
            }
            if (investBaseInfo.qiaosui==1){
                check_type4.setChecked(true);
            }
            nextStep.setVisibility(View.GONE);
        }else{
            surveyPeople.setText(userInfo.username);
            surveyDate.setText(DateUtil.getCurrentDate(DateUtil.format1));
        }
    }

    public void setListener() {

        
        
        surveyTaskSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv= (TextView) view;
                if(tv==null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this,R.style.singleline_text);

                if(investBaseInfo==null) {
                    int selectIndex=surveyLineSpi.getSelectedItemPosition();
                    RouteSurveyTaskBean task = (RouteSurveyTaskBean) surveyTaskSpi.getItemAtPosition(i);
                    surveyLineSpi.setAdapter(getArrayAdapter(dbHelper.getSurveyRouteInfo(task.getiD())));
                    if(selectIndex<surveyLineSpi.getAdapter().getCount())
                        surveyLineSpi.setSelection(selectIndex);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        surveyLineSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv= (TextView) view;
                if(tv==null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this,R.style.singleline_text);

                if(investBaseInfo==null) {
                    RouteSurveyTaskDetailBean routeInfo = (RouteSurveyTaskDetailBean) surveyLineSpi.getSelectedItem();
                    roadItemInfos= dbHelper.getSurveyTaskItemInfo(routeInfo.getiD());
                    updateRoadLevelItems();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        surveyRoadLevelSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv= (TextView) view;
                if(tv==null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this,R.style.singleline_text);
                if(investBaseInfo==null) {
                    updateRoadTypeItems();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });

        surveyRoadTypeSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv= (TextView) view;
                if(tv==null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this,R.style.singleline_text);
                if(investBaseInfo==null) {
                    updateRoadDirectItems();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        surveyDirectSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv = (TextView) view;
                if (tv == null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this, R.style.singleline_text);

                if(investBaseInfo==null) {
                    updateRoadItems();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        surveyRoadItemSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv = (TextView) view;
                if (tv == null)
                    return;
                tv.setTextAppearance(TrafficInvestBaseInfoActivity.this, R.style.singleline_text);

                if(investBaseInfo==null) {
                    RouteSurveyTaskItemBO itemInfo = (RouteSurveyTaskItemBO) surveyRoadItemSpi.getSelectedItem();

                    startKm_et.setText(itemInfo.getStartPotKm() + "");
                    startMeter_et.setText(itemInfo.getStartPotMeter() + "");
                    endKm_et.setText(itemInfo.getEndPotKm() + "");
                    endMeter_et.setText(itemInfo.getEndPotMeter() + "");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });

        surveyTypeSpi.setOnItemSelectedListener(spinnerItemSelectedListener);

      //  surveyDirectSpi.setOnItemSelectedListener(spinnerItemSelectedListener);

        nextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	if(check_type1.isChecked() || check_type2.isChecked() || check_type3.isChecked() || check_type4.isChecked()){
                saveInvestBaseInfo();
            	}else{
            		Toast.makeText(TrafficInvestBaseInfoActivity.this, "请选择要调查的项", Toast.LENGTH_LONG).show();
            	}
            }
        });
    }

    private void updateRoadItems() {
        String level=surveyRoadLevelSpi.getSelectedItem().toString();
        String type=surveyRoadTypeSpi.getSelectedItem().toString();
        String direct=surveyDirectSpi.getSelectedItem().toString();

        List<RouteSurveyTaskItemBO> roadItem=new ArrayList<RouteSurveyTaskItemBO>();
        for(RouteSurveyTaskItemBO item:roadItemInfos) {
            if((level.equals("全部")||item.getRouteGrade().equals(level))&&
                    (type.equals("全部")||item.getRoudBedType().equals(type))&&
                    (direct.equals("全部")||item.getSurveyType().equals(direct)))
                roadItem.add(item);
        }
        surveyRoadItemSpi.setAdapter(getArrayAdapter(roadItem));
    }

    private void updateRoadDirectItems(){
        String level=surveyRoadLevelSpi.getSelectedItem().toString();
        String type=surveyRoadTypeSpi.getSelectedItem().toString();

        Set<String> roadDirect=new HashSet<String>();
        for(RouteSurveyTaskItemBO item:roadItemInfos) {
            if((level.equals("全部")||item.getRouteGrade().equals(level))&&
                    (type.equals("全部")||item.getRoudBedType().equals(type)))
                roadDirect.add(item.getSurveyType());
        }
        List<String> lev=new ArrayList<String>();
        lev.addAll(roadDirect);
        Collections.sort(lev);
        lev.add(0,"全部");

        surveyDirectSpi.setAdapter(getArrayAdapter(lev));
    }

    private void updateRoadTypeItems() {
        String level=surveyRoadLevelSpi.getSelectedItem().toString();
        Set<String> roadType=new HashSet<String>();
        for(RouteSurveyTaskItemBO item:roadItemInfos) {
            if((level.equals("全部")||item.getRouteGrade().equals(level))&&item.getRoudBedType()!=null)
                roadType.add(item.getRoudBedType());
        }
        List<String> lev=new ArrayList<String>();
        lev.addAll(roadType);
        Collections.sort(lev);
        lev.add(0,"全部");

        surveyRoadTypeSpi.setAdapter(getArrayAdapter(lev));
    }



    private void updateRoadLevelItems() {
        Set<String> levels=new HashSet<String>();
        for(RouteSurveyTaskItemBO item:roadItemInfos) {
            levels.add(item.getRouteGrade());
        }
        List<String> lev=new ArrayList<String>();
        lev.addAll(levels);
        Collections.sort(lev);
        lev.add(0,"全部");

        surveyRoadLevelSpi.setAdapter(getArrayAdapter(lev));
    }

    private void saveInvestBaseInfo() {
        int startKm=getIntegerValue(startKm_et);
        int startMeter=getIntegerValue(startMeter_et);
        int endKm=getIntegerValue(endKm_et);
        int endMeter=getIntegerValue(endMeter_et);

        RouteSurveyTaskItemBO routeInfo= (RouteSurveyTaskItemBO) surveyRoadItemSpi.getSelectedItem();
        if(routeInfo==null) {
            showToast("请先选择线路");
            return;
        }
        int maxValue=routeInfo.getEndPotKm()*1000+routeInfo.getEndPotMeter();
        int minValue=routeInfo.getStartPotKm()*1000+routeInfo.getStartPotMeter();

        int curStart=startKm*1000+startMeter;
        int curEnd=endKm*1000+endMeter;

        if(startKm==-1||startMeter==-1||endKm==-1||endMeter==-1){
            showToast("请输入完整起始、终点桩号信息");
        }else if(curStart>curEnd){
            showToast("起始桩号不能大于终点桩号");
        }else if(curStart<minValue||curStart>maxValue||curEnd<minValue||curEnd>maxValue){
            showToast("起始、终点桩号不能超过线路桩号范围");
        }else{
            boolean isInsert = investBaseInfo == null;
            if(isInsert) {
                investBaseInfo = new TrafficInvestBaseInfo();
                investBaseInfo.setID(PKCreator.getPrimaryKey());
                investBaseInfo.setSurveyDate(DateUtil.getCurrentDate(DateUtil.format2));
                investBaseInfo.setSurveyer(userInfo.getUsername());
                investBaseInfo.setSurveyerID(userInfo.getRyid());
                investBaseInfo.setOrgID(userInfo.bmcode+"");
                investBaseInfo.setOrgName(userInfo.bmname);
            }
            investBaseInfo.setRoudBedType(routeInfo.getRoudBedType());
            investBaseInfo.setRoadLevel(routeInfo.getRouteGrade());
            investBaseInfo.setSurveyWay(routeInfo.getSurveyType());
            investBaseInfo.setSurveyLine(((RouteSurveyTaskDetailBean)surveyLineSpi.getSelectedItem()).getRouteName());
            investBaseInfo.setDetailID(routeInfo.getiD());
            investBaseInfo.setStartPot(routeInfo.getStartPot());
            investBaseInfo.setEndPot(routeInfo.getEndPot());
            investBaseInfo.setStartPotKm(startKm);
            investBaseInfo.setStartPotMeter(startMeter);
            investBaseInfo.setEndPotKm2(endKm);
            investBaseInfo.setEndPotMeter2(endMeter);
            investBaseInfo.setSurveyType(surveyTypeSpi.getSelectedItem().toString());
            investBaseInfo.setSurveyTask(surveyTaskSpi.getSelectedItem().toString());
            investBaseInfo.setTimeStamp(System.currentTimeMillis());
            if(check_type2.isChecked()) {
                investBaseInfo.setLuji(1);
            }else {
                investBaseInfo.setLuji(0);
            }
            if(check_type4.isChecked()) {
                investBaseInfo.setQiaosui(1);
            }else {
                investBaseInfo.setQiaosui(0);
            }if(check_type3.isChecked()) {
                investBaseInfo.setYanxian(1);
            }else {
                investBaseInfo.setYanxian(0);
            }
            if (check_type1.isChecked()) {
                investBaseInfo.setLumian(1);
            }else {
                investBaseInfo.setLumian(0);
            }
            if (isInsert) {
                dbHelper.insertInvestBaseInfo(investBaseInfo);
            }else{
                dbHelper.updateInvestBaseInfo(investBaseInfo);
            }
            UIHelper.startInvestDetailCatalogActivity(this,investBaseInfo);
            UIHelper.ToastMessageCenter(this, "信息保存成功");
            finish();
        }

    }

    public void initView() {
        super.initView();
        nextStep= (Button) findViewById(R.id.traffic_invest_base_info_nextStep);
        surveyLineSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_roadLine);
        surveyRoadLevelSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_roadLevel);
        surveyRoadTypeSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_roadType);
        surveyDirectSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_investDirect);
        surveyRoadItemSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_roadItem);
        surveyDate= (EditText) findViewById(R.id.traffic_invest_base_info_investDate);
        surveyPeople= (EditText) findViewById(R.id.traffic_invest_base_info_people);
        startKm_et = (EditText) findViewById(R.id.traffic_invest_base_info_starttKm);
        startMeter_et = (EditText) findViewById(R.id.traffic_invest_base_info_startMeter);
        endKm_et = (EditText) findViewById(R.id.traffic_invest_base_info_endKm);
        endMeter_et = (EditText) findViewById(R.id.traffic_invest_base_info_endMeter);
        surveyTypeSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_investType);
        //surveySelectSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_investSelect);//选择调查项
        surveyTaskSpi= (Spinner) findViewById(R.id.traffic_invest_base_info_investTask);
        check_type1=(CheckBox)findViewById(R.id.liqing);
        check_type2=(CheckBox)findViewById(R.id.luji);
        check_type3=(CheckBox)findViewById(R.id.yanxian);
        check_type4=(CheckBox)findViewById(R.id.qiaosui);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.traffic_invest_base_info_view;
    }

    AdapterView.OnItemSelectedListener spinnerItemSelectedListener= new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            TextView tv= (TextView) view;
            if(tv==null)
                return;
            tv.setTextAppearance(TrafficInvestBaseInfoActivity.this,R.style.singleline_text);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {}
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(TrafficInvestBaseInfoActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("公路技术状况调查信息编辑");

    }
}
